import 'package:flutter_admin/api/odoo/dynamic_data_api.dart';
import 'package:flutter_admin/constants/constant.dart';
import 'package:flutter_admin/models/odoo/dms_file.dart';
import 'package:flutter_admin/models/odoo/res_partner.dart';
import 'package:flutter_admin/pages/common/cry/common/application_context.dart';
import 'package:flutter_admin/pages/common/cry/cry.dart';
import 'package:flutter_admin/pages/common/cry/cry_button_bar.dart';
import 'package:flutter_admin/pages/common/cry/cry_buttons.dart';
import 'package:flutter_admin/pages/common/cry/cry_dialog.dart';
import 'package:flutter_admin/pages/common/cry/form/cry_input.dart';
import 'package:flutter_admin/pages/common/cry/form/cry_select.dart';
import 'package:flutter_admin/pages/common/cry/form/cry_select_date.dart';
import 'package:flutter_admin/pages/common/cry/model/application.dart';
import 'package:flutter_admin/pages/common/cry/model/order_item_model.dart';
import 'package:flutter/material.dart';
import 'package:flutter_admin/pages/common/cry/cry_button.dart';
import 'package:flutter_admin/pages/common/cry/cry_data_table.dart';
import 'package:flutter_admin/api/odoo/purchase_qualifications_file_odoo_api.dart';
import 'package:flutter_admin/constants/enum.dart';
import 'package:flutter_admin/generated/l10n.dart';
import 'package:flutter_admin/pages/common/cry/model/page_model.dart';
import 'package:flutter_admin/pages/common/cry/model/response_body_api.dart';
import 'package:flutter_admin/models/odoo/purchase_qualifications_file.dart';
import 'package:flutter_admin/pages/common/cry/utils/cry_utils.dart';
import 'package:flutter_admin/pages/odoo/res_purchase/purchase_qualifications_file/purchase_qualifications_file_dialog.dart';
import 'package:flutter_admin/pages/odoo/res_purchase/purchase_qualifications_file/purchase_qualifications_file_uplaod.dart';
import 'package:flutter_admin/utils/adaptive_util.dart';
import 'package:flutter_admin/utils/store_util.dart';
import 'package:flutter_admin/utils/utils.dart';

class PurchaseQualificationsFileList extends StatefulWidget {

  final String? suppliercode;

  PurchaseQualificationsFileList({Key? key,required this.suppliercode}) : super(key: key);

  @override
  _PurchaseQualificationsFileListState createState() => _PurchaseQualificationsFileListState();
}

class _PurchaseQualificationsFileListState extends State<PurchaseQualificationsFileList> {
  final GlobalKey<CryDataTableState> tableKey = GlobalKey<CryDataTableState>();
  final GlobalKey<ScaffoldState> scaffoldStateKey = GlobalKey<ScaffoldState>();
  PageModel page = PageModel(orders: [OrderItemModel(column: 'create_date',asc: false)]);
  PurchaseQualificationsFile purchaseQualificationsFile = PurchaseQualificationsFile();
  List<PurchaseQualificationsFile> selectedList = [];
  @override
  void initState() {
    super.initState();
    purchaseQualificationsFile.suppliercode = widget.suppliercode;
    WidgetsBinding.instance!.addPostFrameCallback((c) {
      _query();
    });
  }

  @override
  Widget build(BuildContext context) {
    CryDataTable table = CryDataTable(
      key: tableKey,
      title: "数据列表",
      actions: !isDisplayDesktop(context)
        ? [ _operationList(), ] : [],
      onPageChanged: (firstRowIndex) {
        page.current = (firstRowIndex ~/ page.size + 1);
        _loadData();
      },
      onRowsPerPageChanged: (int size) {
        page.size = size;
        page.current = 1;
        _loadData();
      },
      onSelectChanged: (Map selected) {
        this.setState(() {});
      },
      columns: [
        DataColumn(
          label: Text('企业资质文件'),
          //onSort: (int columnIndex, bool ascending) => _sort('create_date'),
        ),
        DataColumn(
          label: Text('发证机构'),
          //onSort: (int columnIndex, bool ascending) => _sort('create_date'),
        ),
        DataColumn(
          label: Text('发证日期'),
          //onSort: (int columnIndex, bool ascending) => _sort('create_date'),
        ),
        DataColumn(
          label: Text('有效截止日期'),
          //onSort: (int columnIndex, bool ascending) => _sort('create_date'),
        ),
        DataColumn(
          label: Text('备注'),
          //onSort: (int columnIndex, bool ascending) => _sort('create_date'),
        ),
	        DataColumn(
          label: Text('附件名称'),
          //onSort: (int columnIndex, bool ascending) => _sort('create_date'),
        ),
        DataColumn(
          label: Text('创建人'),
          //onSort: (int columnIndex, bool ascending) => _sort('create_date'),
        ),
        DataColumn(
          label: Text('创建时间'),
          //onSort: (int columnIndex, bool ascending) => _sort('create_date'),
        ),
      ],
      getCells: (m) {
        PurchaseQualificationsFile purchaseQualificationsFile = PurchaseQualificationsFile.fromMap(m);
        return [
          DataCell(Text(purchaseQualificationsFile.qualificationsname ?? '--')),
          DataCell(Text(purchaseQualificationsFile.issuingauthority ?? '--')),
          DataCell(Text(purchaseQualificationsFile.issuingdate ?? '--')),
          DataCell(Text(purchaseQualificationsFile.expirydate ?? '--')),
          DataCell(Text(purchaseQualificationsFile.remark ?? '--')),
          DataCell(Text(purchaseQualificationsFile.filename ?? '--')),
          DataCell(Text(purchaseQualificationsFile.createName ?? '--')),
          DataCell(Text(Utils.timeUTC(purchaseQualificationsFile.createDate))),
        ];
      },
    );
    _getSelectList();
    CryButtonBar buttonBar = CryButtonBar(
      children: <Widget>[
        CryButton(
            label: "上传",
            iconData: Icons.upload_rounded,
            onPressed: () => _upload()),
        CryButton(
            label: "下载",
            iconData: Icons.download_rounded,
            onPressed:
            selectedList.length != 1 ? null : () => _download(selectedList[0])),
        CryButtons.delete(context,
            selectedList.length < 1 ? null : () => _delete(selectedList)),
      ],
    );
    var result = Scaffold(
      key: scaffoldStateKey,
      appBar: AppBar(
        leading: Builder(
          builder: (BuildContext context) {
            final ScaffoldState? scaffold = Scaffold
                .maybeOf(context);
            final ModalRoute<Object?>? parentRoute = ModalRoute.of(context);
            final bool canPop = parentRoute?.canPop ?? false;

            if (canPop) {
              return BackButton();
            } else {
              return SizedBox.shrink();
            }
          },
        ),
        title: Text('企业资质文件'),
      ),
      body: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        crossAxisAlignment: CrossAxisAlignment.start,
        children: <Widget>[
          SizedBox(height: 10),
          // isDisplayDesktop(context)?form:Container(),
          isDisplayDesktop(context)?buttonBar:Container(),
          Expanded(child: SingleChildScrollView(child: table)),
        ],
      ),
    );
    return result;
  }

  _upload() async {
    showDialog(
      context: context,
      builder: (BuildContext context) => Dialog(
        child: PurchaseQualificationsFileUpload(
          suppliercode: widget.suppliercode,
        ),
      ),
    ).then((v) {
      if (v != null) {
        _query();
      }
    });
  }

  _download(PurchaseQualificationsFile purchaseQualificationsFile) async{
    //todo/web/content?model=dms.file&id=87&field=content&download=true
    Application application = ApplicationContext.instance.application;
    var odooBaseUrl =application.odooBaseUrl!;
    var data = StoreUtil.read(Constant.CLIENT);
    String documentno = purchaseQualificationsFile.suppliercode!+"-"+purchaseQualificationsFile.id!;
    ResponseBodyApi res = await DynamicDataApi.getModels(model: "dms.file",key: 'documentno',val: documentno);
    if(res.success!){
      Utils.launchURL("${odooBaseUrl}web/quninmadexiazaiwenjian/${data['login']}&${data['password']}&${res.data[0]['id']}");
    }
  }

  _query() {
    tableKey.currentState?.pageTo(0);
    _loadData();
  }

  _loadData() async {
    ResponseBodyApi responseBodyApi = await PurchaseQualificationsFileOdooApi.page(
        data:{"page": page,"domainList":purchaseQualificationsFile.toDomainList()});
    if(responseBodyApi.success!){
      page = responseBodyApi.data != null ? responseBodyApi.data : PageModel();
      tableKey.currentState!.loadData(page);
      _getSelectList();
    }
  }

  _delete(List<PurchaseQualificationsFile> selectedList) async {
   cryConfirm(context, S.of(context).confirmDelete,
                  (context) async {
        List ids = selectedList.map((v) {
           return int.parse(v.id!);
        }).toList();
        var result = await PurchaseQualificationsFileOdooApi.removeByIds(ids);
        if (result.success!) {
          _query();
          CryUtils.message(S.of(Cry.context).success);
        }
     });
  }

  _sort(column, {ascending}) {
    page.orders[0].column = column;
    page.orders[0].asc = ascending ?? !page.orders[0].asc!;
    _query();
  }

  _search() {
    return showDialog(
      context: context,
      builder: (BuildContext context) => Dialog(
        child: PurchaseQualificationsFileDialog(),
      ),
    ).then((v) {
      if (v != null) {
        purchaseQualificationsFile = v;
        _query();
      }
    });
  }

  _getSelectList(){
    selectedList = tableKey.currentState
        ?.getSelectedList(page)
        .map<PurchaseQualificationsFile>((e) => PurchaseQualificationsFile.fromMap(e))
        .toList() ??
        [];
    setState(() { });
  }

  _operationList() {
    return  PopupMenuButton(
      onSelected: (dynamic v) {
        if (v == OperationType.query) {
          // _search();
        } else if (v == OperationType.add) {
          //todo 这里偷个懒 利用添加和修改枚举代替上传下载
          //上传
          // _upload(selectedList[0]);
        } else if (v == OperationType.edit) {
          //下载
          // _download(selectedList[0].id);
        } else if (v == OperationType.delete) {
          cryConfirm(context, S.of(context).confirmDelete,
                  (context) async {
                _delete(selectedList);
              });
        }
      },
      itemBuilder: (context) => <PopupMenuEntry<OperationType>>[
        PopupMenuItem<OperationType>(
          value: OperationType.add,
          child: ListTile(
            leading: const Icon(Icons.upload_rounded),
            title: Text('上传'),
          ),
        ),
        PopupMenuItem<OperationType>(
          value: OperationType.edit,
          enabled: selectedList.length == 1,
          child: ListTile(
            enabled: selectedList.length == 1,
            leading: const Icon(Icons.download_rounded),
            title: Text('下载'),
          ),
        ),
        PopupMenuItem<OperationType>(
          value: OperationType.delete,
          enabled: selectedList.length != 0,
          child: ListTile(
            leading: const Icon(Icons.delete), //Icons.delete
            enabled: selectedList.length != 0,
            title: Text('删除'),
          ),
        ),
      ],
    );
  }
}